package com.hivekion.common.validate;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

public class ImageUtil {

      /**
       * 生成验证码图片
       *
       * @param request         设置session
       * @param response        转成图片
       * @param captchaProducer 生成图片方法类
       * @throws Exception
       */
      public static void validateCode(
	      HttpServletRequest request,
	      HttpServletResponse response,
	      DefaultKaptcha captchaProducer,
	      String capText,
	      String validateSessionKey)
	      throws Exception {
	    response.setDateHeader("Expires", 0);
	    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	    response.setHeader("Pragma", "no-cache");
	    response.setContentType("image/jpeg");
	    request.getSession().setAttribute(validateSessionKey, capText);
	    BufferedImage bi = captchaProducer.createImage(capText);
	    ServletOutputStream out = response.getOutputStream();
	    ImageIO.write(bi, "jpg", out);
	    try {
		  out.flush();
	    } finally {
		  out.close();
	    }
      }
}
